package Part3_UDP;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: Demo
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.26 23:12
 */
public class UDP {
    @Test
    public void sender() throws IOException {

        //创建DatagramSocket实例
        DatagramSocket socket = new DatagramSocket();

        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port = 8989;

        byte[] bytes = "我是发送端".getBytes(StandardCharsets.UTF_8);

        //创建DatagramPacket实例，封装数据、长度、ip、端口
        DatagramPacket packet = new DatagramPacket(bytes, 0,bytes.length,inetAddress,port);

        //发送数据
        socket.send(packet);

        socket.close();
    }

    @Test
    public void receiver() throws IOException{

        //创建DatagramSocket实例
        DatagramSocket socket = new DatagramSocket(8989);

        //创建数据报对象，用于接收
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0,buffer.length);

        //接收数据
        socket.receive(packet);

        byte[] data = packet.getData();
        String s = new String(data, 0, packet.getLength());
        System.out.println(s);

        socket.close();
    }
}
